<template>
  <div class="refund-audit">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>退款审核管理</span>
          <el-button-group>
            <el-button type="primary" @click="handleBatchAudit"
              >批量审核</el-button
            >
            <el-button type="success" @click="exportData">导出数据</el-button>
          </el-button-group>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="退款类型">
          <el-select
            v-model="searchForm.refundType"
            placeholder="请选择退款类型"
          >
            <el-option label="门票退款" value="ticket" />
            <el-option label="酒店退款" value="hotel" />
            <el-option label="套餐退款" value="package" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="searchForm.status" placeholder="请选择审核状态">
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="已退款" value="refunded" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="refundList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="refundNo" label="退款编号" width="180" />
        <el-table-column prop="orderNo" label="订单编号" width="180" />
        <el-table-column prop="refundType" label="退款类型" width="120">
          <template #default="{ row }">
            <el-tag>{{ getRefundTypeLabel(row.refundType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="退款金额" width="120">
          <template #default="{ row }"> ¥{{ row.amount.toFixed(2) }} </template>
        </el-table-column>
        <el-table-column
          prop="reason"
          label="退款原因"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column prop="applyTime" label="申请时间" width="160" />
        <el-table-column prop="status" label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="primary"
                size="small"
                :disabled="row.status !== 'pending'"
                @click="handleAudit(row)"
              >
                审核
              </el-button>
              <el-button
                type="success"
                size="small"
                :disabled="row.status !== 'approved'"
                @click="handleRefund(row)"
              >
                退款
              </el-button>
              <el-button type="info" size="small" @click="viewDetail(row)">
                详情
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <template #empty>
        <div class="empty-state">
          <el-empty 
            description="暂无退款数据" 
            :image-size="200"
          >
            <div class="empty-text">暂无退款审核数据</div>
            <div class="empty-subtext">用户申请退款后将在此处显示</div>
          </el-empty>
        </div>
      </template>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog v-model="auditDialogVisible" title="退款审核" width="600px">
      <el-form
        ref="formRef"
        :model="auditForm"
        :rules="auditRules"
        label-width="100px"
      >
        <el-form-item label="审核结果" prop="result">
          <el-radio-group v-model="auditForm.result">
            <el-radio label="approved">通过</el-radio>
            <el-radio label="rejected">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="退款金额"
          prop="amount"
          v-if="auditForm.result === 'approved'"
        >
          <el-input-number
            v-model="auditForm.amount"
            :min="0"
            :max="currentRefund.orderAmount"
            :precision="2"
            :step="0.1"
            style="width: 200px"
          />
          <span class="amount-tip"
            >最大可退: ¥{{ currentRefund.orderAmount?.toFixed(2) }}</span
          >
        </el-form-item>
        <el-form-item label="审核说明" prop="comment">
          <el-input
            v-model="auditForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入审核说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAudit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 退款对话框 -->
    <el-dialog v-model="refundDialogVisible" title="确认退款" width="500px">
      <el-form
        ref="refundFormRef"
        :model="refundForm"
        :rules="refundRules"
        label-width="100px"
      >
        <el-form-item label="退款金额">
          <div class="refund-amount">
            ¥{{ currentRefund.amount?.toFixed(2) }}
          </div>
        </el-form-item>
        <el-form-item label="退款方式" prop="method">
          <el-radio-group v-model="refundForm.method">
            <el-radio label="auto">自动退款</el-radio>
            <el-radio label="manual">手动退款</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="退款说明" prop="comment">
          <el-input
            v-model="refundForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入退款说明"
          />
        </el-form-item>
        <el-form-item label="退款凭证" v-if="refundForm.method === 'manual'">
          <el-upload
            class="upload-demo"
            action="/api/admin/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            multiple
            :limit="3"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持jpg/png/pdf格式，单个文件不超过5MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="refundDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRefund">确定退款</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="退款详情" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="退款编号">{{
          currentRefund.refundNo
        }}</el-descriptions-item>
        <el-descriptions-item label="订单编号">{{
          currentRefund.orderNo
        }}</el-descriptions-item>
        <el-descriptions-item label="退款类型">
          <el-tag>{{ getRefundTypeLabel(currentRefund.refundType) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="退款金额"
          >¥{{ currentRefund.amount?.toFixed(2) }}</el-descriptions-item
        >
        <el-descriptions-item label="申请时间">{{
          currentRefund.applyTime
        }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag :type="getStatusTag(currentRefund.status)">
            {{ getStatusLabel(currentRefund.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="退款原因" :span="2">
          {{ currentRefund.reason }}
        </el-descriptions-item>
        <el-descriptions-item label="申请材料" :span="2">
          <div class="refund-materials">
            <el-image
              v-for="(url, index) in currentRefund.materials"
              :key="index"
              :src="url"
              :preview-src-list="currentRefund.materials"
              fit="cover"
              class="material-image"
            />
          </div>
        </el-descriptions-item>
      </el-descriptions>

      <div class="audit-info mt-4" v-if="currentRefund.status !== 'pending'">
        <h4>审核信息</h4>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="审核人">{{
            currentRefund.auditor
          }}</el-descriptions-item>
          <el-descriptions-item label="审核时间">{{
            currentRefund.auditTime
          }}</el-descriptions-item>
          <el-descriptions-item label="审核结果">
            <el-tag :type="getStatusTag(currentRefund.auditResult)">
              {{ getStatusLabel(currentRefund.auditResult) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="审核说明">{{
            currentRefund.auditComment
          }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="refund-info mt-4" v-if="currentRefund.status === 'refunded'">
        <h4>退款信息</h4>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="退款方式">{{
            currentRefund.refundMethod
          }}</el-descriptions-item>
          <el-descriptions-item label="退款时间">{{
            currentRefund.refundTime
          }}</el-descriptions-item>
          <el-descriptions-item label="退款操作人">{{
            currentRefund.refundOperator
          }}</el-descriptions-item>
          <el-descriptions-item label="退款说明">{{
            currentRefund.refundComment
          }}</el-descriptions-item>
          <el-descriptions-item
            label="退款凭证"
            :span="2"
            v-if="currentRefund.refundProofs?.length"
          >
            <div class="refund-materials">
              <el-image
                v-for="(url, index) in currentRefund.refundProofs"
                :key="index"
                :src="url"
                :preview-src-list="currentRefund.refundProofs"
                fit="cover"
                class="material-image"
              />
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="order-info mt-4">
        <h4>订单信息</h4>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="商品名称">{{
            currentRefund.productName
          }}</el-descriptions-item>
          <el-descriptions-item label="订单金额"
            >¥{{ currentRefund.orderAmount?.toFixed(2) }}</el-descriptions-item
          >
          <el-descriptions-item label="下单时间">{{
            currentRefund.orderTime
          }}</el-descriptions-item>
          <el-descriptions-item label="支付方式">{{
            currentRefund.paymentMethod
          }}</el-descriptions-item>
          <el-descriptions-item label="联系人">{{
            currentRefund.contactName
          }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{
            currentRefund.contactPhone
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

// 搜索表单
const searchForm = reactive({
  orderNo: "",
  refundType: "",
  status: "",
  dateRange: [],
});

// 表格数据
const loading = ref(false);
const refundList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedRefunds = ref([]);

// 审核对话框
const auditDialogVisible = ref(false);
const formRef = ref(null);
const auditForm = reactive({
  result: "",
  amount: 0,
  comment: "",
});

// 审核表单验证规则
const auditRules = {
  result: [{ required: true, message: "请选择审核结果", trigger: "change" }],
  amount: [{ required: true, message: "请输入退款金额", trigger: "blur" }],
  comment: [{ required: true, message: "请输入审核说明", trigger: "blur" }],
};

// 退款对话框
const refundDialogVisible = ref(false);
const refundFormRef = ref(null);
const refundForm = reactive({
  method: "auto",
  comment: "",
});

// 退款表单验证规则
const refundRules = {
  method: [{ required: true, message: "请选择退款方式", trigger: "change" }],
  comment: [{ required: true, message: "请输入退款说明", trigger: "blur" }],
};

// 详情对话框
const detailDialogVisible = ref(false);
const currentRefund = ref({});

// 获取退款类型标签
const getRefundTypeLabel = (type) => {
  const types = {
    ticket: "门票退款",
    hotel: "酒店退款",
    package: "套餐退款",
  };
  return types[type] || type;
};

// 获取状态标签
const getStatusLabel = (status) => {
  const statuses = {
    pending: "待审核",
    approved: "已通过",
    rejected: "已拒绝",
    refunded: "已退款",
  };
  return statuses[status] || status;
};

// 获取状态标签样式
const getStatusTag = (status) => {
  const statuses = {
    pending: "warning",
    approved: "success",
    rejected: "danger",
    refunded: "info",
  };
  return statuses[status] || "";
};

// 搜索
const handleSearch = () => {
  // 实现搜索逻辑
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  handleSearch();
};

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedRefunds.value = val;
};

// 批量审核
const handleBatchAudit = () => {
  if (selectedRefunds.value.length === 0) {
    ElMessage.warning("请选择要审核的退款申请");
    return;
  }
  // 实现批量审核逻辑
};

// 导出数据
const exportData = () => {
  // 实现导出逻辑
};

// 审核单个退款
const handleAudit = (row) => {
  currentRefund.value = row;
  auditForm.result = "";
  auditForm.amount = row.amount;
  auditForm.comment = "";
  auditDialogVisible.value = true;
};

// 处理退款
const handleRefund = (row) => {
  currentRefund.value = row;
  refundForm.method = "auto";
  refundForm.comment = "";
  refundDialogVisible.value = true;
};

// 查看详情
const viewDetail = (row) => {
  currentRefund.value = row;
  detailDialogVisible.value = true;
};

// 提交审核
const submitAudit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        // 实现提交审核逻辑
        ElMessage.success("审核成功");
        auditDialogVisible.value = false;
        handleSearch();
      } catch (error) {
        console.error("审核失败：", error);
        ElMessage.error("审核失败");
      }
    }
  });
};

// 提交退款
const submitRefund = () => {
  refundFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        // 实现提交退款逻辑
        ElMessage.success("退款成功");
        refundDialogVisible.value = false;
        handleSearch();
      } catch (error) {
        console.error("退款失败：", error);
        ElMessage.error("退款失败");
      }
    }
  });
};

// 文件上传相关方法
const handlePreview = (file) => {
  // 实现文件预览逻辑
};

const handleRemove = (file, fileList) => {
  // 实现文件移除逻辑
};

const beforeRemove = (file, fileList) => {
  return ElMessageBox.confirm(`确定移除 ${file.name}？`);
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  handleSearch();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  handleSearch();
};

// 页面加载时获取数据
onMounted(() => {
  handleSearch();
});
</script>

<style scoped>
.refund-audit {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.refund-materials {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.material-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  cursor: pointer;
}

.amount-tip {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}

.refund-amount {
  font-size: 24px;
  font-weight: bold;
  color: #f56c6c;
}

.mt-4 {
  margin-top: 20px;
}

.audit-info,
.refund-info,
.order-info {
  margin-top: 20px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

/* 空状态样式 */
.empty-state {
  padding: 40px 0;
  text-align: center;
}

.empty-text {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  margin-top: 10px;
}

.empty-subtext {
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  margin-top: 5px;
}
</style>
